<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisble"
      :close-on-click-modal="false"
      :before-close="cancel"
      width="900px"
      append-to-body>
      <el-steps :active="step" finish-status="success" style="margin-left: 10px">
        <el-step title="基础信息"></el-step>
        <el-step title="联系人"></el-step>
      </el-steps>
      <el-form ref="customForm" :model="customForm" :rules="customFormRules" label-width="100px">
        <div v-if="pageIndex==1" style="margin-top: 20px">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="客户来源" prop="sourceType">
                <el-select v-model="customForm.sourceType" clearable @change="sourceTypeChanged" placeholder="请选择客户来源" style="width: 100%">
                  <el-option
                    v-for="dict in sourceOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12"  v-if="customForm.sourceType==='2'">
              <el-form-item label="新媒体平台" prop="merchatPlatform">
                <el-select v-model="customForm.merchantPlatform" clearable placeholder="请选择平台类型" style="width: 100%">
                  <el-option
                    v-for="dict in newMediaPlatOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12"  v-if="customForm.sourceType==='1'">
              <el-form-item label="微信账号" prop="wechatNo">
                <el-input v-model="customForm.wechatNo" clearable placeholder="请填写微信账号" style="width: 100%">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="customForm.sourceType==='2' || customForm.sourceType === '1'" :gutter="10">
            <el-col :span="12">
              <el-form-item label="商家账号" prop="merchantAccount">
                <el-input v-model="customForm.merchantAccount" clearable placeholder="请输入商家账号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商家电话" prop="merchantTel">
                <el-input v-model="customForm.merchantTel" clearable placeholder="请输入商家电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider style="margin-top: -10px"></el-divider>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="店铺名称" prop="cusname">
                <el-input v-model="customForm.cusname" clearable placeholder="请输入店铺名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="电商平台" prop="platformType">
                <el-select v-model="customForm.platformType" clearable placeholder="请选择平台类型" style="width: 100%">
                  <el-option
                    v-for="dict in platformOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="customForm.platformType==='1'||customForm.platformType==='2'">
              <el-form-item label="旺旺号" prop="aliww">
                <el-input v-model="customForm.aliww" clearable placeholder="请输入旺旺号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="所属类目" prop="groupName">
                <el-input v-model.trim="customForm.groupName" placeholder="请填写所属类目"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="公司名称" prop="company">
                <el-input v-model="customForm.company" clearable placeholder="请输入公司名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="店铺网址" prop="shopUrl">
                <el-input v-model="customForm.shopUrl" clearable placeholder="请输入店铺网址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="店铺账号" prop="account">
                <el-input v-model="customForm.account" placeholder="请填写店铺账号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="店铺密码" prop="password">
                <el-input type="password" v-model="customForm.password" placeholder="请填写店铺密码" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="企业群" prop="wechatGroup">
                <el-input v-model.trim="customForm.wechatGroup" placeholder="请填写企业群名称" clearable ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" v-if="menu=='shop'">
            <el-form-item label="销售人员" prop="userId">
              <el-cascader
                v-model="customForm.deptUser"
                :options="userOptions"
                :normalizer="user_normalizer"
                @change="handleChangeUser"
                clearable
                placeholder="请选择首次销售人员"
                style="width: 100%"></el-cascader>
            </el-form-item>
          </el-row>
          <el-row :gutter="10" style="text-align: right; margin-top: 20px">
            <el-button type="primary" @click="next" v-prevent-re-click>下一步</el-button>
          </el-row>
        </div>
        <div v-if="pageIndex==2" style="margin-top: 20px">
          <el-row :gutter="10">
            <el-button type="primary" @click="handleAddContact" style="margin-bottom: 20px">添加联系人</el-button>
          </el-row>
          <el-row :gutter="10">
            <el-table v-loading="loading" :data="customForm.contacts">
              <el-table-column label="序号" type="index" width="50" align="center" />
              <el-table-column label="姓名" prop="name" width="120" align="center" />
              <el-table-column label="性别" prop="sex" width="80" align="center" :formatter="sexFormat"/>
              <el-table-column label="联系电话" prop="tel" width="150" align="center" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdateContact(scope.row)"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDeleteContact(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row :gutter="10" style="text-align: right; margin-top: 20px">
            <el-button @click="prev" v-prevent-re-click>上一步</el-button>
            <el-button type="primary" @click="submitForm" v-prevent-re-click>确 定</el-button>
          </el-row>
        </div>
      </el-form>
    </el-dialog>

    <!-- 增加/修改联系人 -->
    <el-dialog :title="contactTitle" :visible.sync="openContactDialog" width="600px" append-to-body>
      <el-form ref="contactForm" :model="contactForm" :rules="contactFormRules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model.trim="contactForm.name" clearable placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="contactForm.sex" clearable placeholder="请选择性别" style="width: 100%">
                <el-option
                  v-for="dict in sexOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="电话" prop="tel">
              <el-input v-model.trim="contactForm.tel" clearable required placeholder="请输入电话" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitContactForm" v-prevent-re-click>确 定</el-button>
        <el-button @click="cancelContactForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selectAllDeptUser } from '@/api/system/user'
import {
  addContact,
  deleteContact,
  getContactInfo,
  insertCustomByOperator,
  listContact,
  updateContact, updateCustom
} from '@/api/custom/custom'
import { mapGetters } from 'vuex'

export default {
  name: 'editcustom',
  props: [ "dialogVisble", "title", "menu", "dataModel", "active" ],
  computed: {
    ...mapGetters([
      'userid'
    ]),
    customForm: {
      set(value) {

      },
      get() {
        return this.dataModel
      }
    },
    step() {
      return this.pageIndex
    }
  },
  data() {
    return {
      pageIndex: this.active,
      // 是否显示加载动画
      loading: false,
      // 联系人弹窗标题
      contactTitle: '',
      // 打开联系人弹窗
      openContactDialog: false,
      // 客户表单校验项
      customFormRules: {
        wechatNo: [
          { required: true, message: "微信账号不能为空", trigger: ['blur', 'change'] }
        ],
        // merchantPlatform: [
        //   { required: true, message: "新媒体平必须选择台类型", trigger: ['blur', 'change'] }
        // ],
        // merchantAccount: [
        //   { required: true, message: "商家账号不能为空", trigger: ['blur', 'change'] }
        // ],
        // merchantTel: [
        //   { required: true, message: "商家电话不能为空", trigger: ['blur', 'change'] }
        // ]
      },
      // 平台类型选项
      platformOptions: [],
      // 等级类型选项
      levelOptions: [],
      // 行业类型选项
      industryOptions: [],
      // 用户
      userOptions: [],
      // 性别选项
      sexOptions: [],
      // 客户来源选项
      sourceOptions: [],
      // 新媒体平台选项
      newMediaPlatOptions: [],
      // 联系人表单
      contactForm: {
        id: '',
        customId: '',
        name: '',
        sex: '',
        tel: ''
      },
      // 联系人表单校验规则
      contactFormRules: {
        tel: [
          { required: true, message: "联系人电话不能为空", trigger: ['blur', 'change'] },
          { min:1, max: 20, message: '长度应该为1-20个字符', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created() {
    this.getDicts("custom_platform").then(response => {
      this.platformOptions = response.data;
    })
    this.getDicts("custom_level").then(response => {
      this.levelOptions = response.data;
    })
    this.getDicts("custom_industry").then(response => {
      this.industryOptions = response.data;
    })
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    })
    this.getDicts("custom_source").then(response => {
      this.sourceOptions = response.data;
    })
    this.getDicts("new_media_platform").then(response => {
      this.newMediaPlatOptions = response.data;
    })
    this.selectDeptUserTree()
    this.initActive()
  },
  methods: {
    // 性别格式化
    sexFormat(row) {
      if(row.sex === '0') {
        return '男'
      } else if(row.sex === '1') {
        return '女'
      } else {
        return '未知'
      }
    },
    // 查询部门人员
    selectDeptUserTree(){
      selectAllDeptUser().then(response => {
        this.userOptions = this.handleTree(response.data, "userId");
      })
    },
    user_normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.userId,
        label: node.nickName,
        children: node.children
      }
    },
    // 切换销售人员
    handleChangeUser() {
      this.customForm.allocationUserId = this.customForm.deptUser[this.customForm.deptUser.length - 1]
      this.customForm.allocationStatus = '1'
    },
    // 下一步
    next() {
      this.$refs.customForm.validate(valid => {
        if(valid) {
          this.pageIndex++
        }
      })
    },
    // 上一步
    prev() {
      this.pageIndex--
    },
    // 重置表单数据
    resetCustomForm() {
      this.pageIndex = 1
      this.customForm = {
        id: '',
        platformType: '',
        cusname: '',
        level: '',
        groupName: '',
        company: '',
        adddress: '',
        industryId: '',
        allocationStatus: '',
        allocationUserId: '',
        allocationTime: '',
        shopUrl: '',
        account: '',
        password: '',
        wechatGroup: '',
        status: '',
        operStatus: '',
        contacts: [{
          name: '',
          sex: '',
          birth: '',
          duties: '',
          tel: '',
          wechat: '',
          qq: ''
        }],
        deptUser: []
      }
      this.resetForm('customForm')
    },
    // 提交表单数据
    submitForm() {
      if(this.menu === 'custom') {
        this.customForm.status = '0'
      } else if(this.menu === 'shop') {
        this.customForm.status = '2'
      }

      this.$refs.customForm.validate(valid => {
        if(valid) {
          updateCustom(this.customForm).then(response => {
            this.$message.success('修改成功！')
            this.resetCustomForm()
            this.$emit('closeEditCustomDialog', true)
          })
        }
      })
    },
    // 关闭弹窗
    cancel() {
      this.pageIndex = 1
      this.resetCustomForm()
      this.$emit('closeEditCustomDialog', false)
    },
    // 查询联系人
    getContactList() {
      listContact(this.customForm.id).then(response =>{
        console.log('联系人：' + JSON.stringify(response.rows))
        this.customForm.contacts = response.rows
      })
    },
    // 新增联系人
    handleAddContact() {
      this.resetContactForm()
      this.openContactDialog = true
      this.contactTile = '添加联系人'
    },
    // 修改联系人
    handleUpdateContact(row) {
      getContactInfo(row.id).then(response => {
        if(response.code === 200) {
          this.contactForm = response.data
          this.openContactDialog = true
          this.contactTile = '修改联系人'
        }
      })
    },
    // 删除联系人
    handleDeleteContact(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的联系人?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return deleteContact(row.id);
      }).then(() => {
        this.getContactList()
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },
    // 提交联系人表单
    submitContactForm() {
      this.$refs['contactForm'].validate(valid => {
        if(valid) {
          if(this.contactForm.id === undefined || this.contactForm.id === ''){
            this.contactForm.customId = this.customForm.id
            addContact(this.contactForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.openContactDialog = false;
                this.getContactList()
              }
            })
          } else {
            updateContact(this.contactForm).then(response => {
              if(response.code === 200) {
                this.msgSuccess("修改成功");
                this.openContactDialog = false;
                this.getContactList()
              }
            })
          }
        }
      })
    },
    // 关闭联系人表单
    cancelContactForm() {
      this.resetContactForm()
      this.openContactDialog = false;
    },
    // 重置联系人表单
    resetContactForm() {
      this.contactForm = {
        id: '',
        customId: '',
        name: '',
        sex: '',
        birth: '',
        duties: '',
        tel: '',
        wechat: '',
        qq: ''
      }
      this.resetForm('contactForm')
    },
    // 切换客户来源
    sourceTypeChanged(){
      if(this.customForm.sourceType === '0'){
        this.customForm.wechatNo = ''
        this.customForm.merchantPlatform = ''
        this.customForm.merchantAccount = ''
        this.customForm.merchantTel = ''
      }else if(this.customForm.sourceType === '1'){
        this.customForm.merchantPlatform = ''
        this.customForm.merchantAccount = ''
        this.customForm.merchantTel = ''
      }else if(this.customForm.sourceType === '2'){
        this.customForm.wechatNo = ''
      }
    }
  }
}
</script>

<style scoped lang="scss">

</style>
